<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/cuphead.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/cuphead.ico?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/cuphead.ico?v=5.1.3">


  <link rel="mask-icon" href="/cuphead.ico?v=5.1.3" color="#222">





  <meta name="keywords" content="教程,shell,">










<meta name="description" content="#shell入门 原文 Shell是什么Shell是指一种应用程序，这个应用程序提供了一个界面，用户通过这个界面访问操作系统内核的服务, Shell脚本（shell script），是一种为Shell编写的脚本程序。我们经常说的shell通常都是指shell脚本。 环境和工具Shell跟java、php、Python编程一样，只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。">
<meta name="keywords" content="教程,shell">
<meta property="og:type" content="article">
<meta property="og:title" content="shell入门">
<meta property="og:url" content="https://mylyed.github.io/2018/01/22/shell/shell_fast_guides/index.html">
<meta property="og:site_name" content="李磊的笔记本">
<meta property="og:description" content="#shell入门 原文 Shell是什么Shell是指一种应用程序，这个应用程序提供了一个界面，用户通过这个界面访问操作系统内核的服务, Shell脚本（shell script），是一种为Shell编写的脚本程序。我们经常说的shell通常都是指shell脚本。 环境和工具Shell跟java、php、Python编程一样，只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-27T14:37:16.410Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shell入门">
<meta name="twitter:description" content="#shell入门 原文 Shell是什么Shell是指一种应用程序，这个应用程序提供了一个界面，用户通过这个界面访问操作系统内核的服务, Shell脚本（shell script），是一种为Shell编写的脚本程序。我们经常说的shell通常都是指shell脚本。 环境和工具Shell跟java、php、Python编程一样，只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://mylyed.github.io/2018/01/22/shell/shell_fast_guides/">





  <title>shell入门 | 李磊的笔记本</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">李磊的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">纸上得来终觉浅，绝知此事要躬行。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://mylyed.github.io/2018/01/22/shell/shell_fast_guides/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="李磊">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="李磊的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">shell入门</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-22T00:00:00+08:00">
                2018年01月22号
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/shell编程/" itemprop="url" rel="index">
                    <span itemprop="name">shell编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>#shell入门</p>
<p><a href="https://github.com/dpm100/fast_guides" target="_blank" rel="noopener">原文</a></p>
<h2 id="Shell是什么"><a href="#Shell是什么" class="headerlink" title="Shell是什么"></a>Shell是什么</h2><p>Shell是指一种应用程序，这个应用程序提供了一个界面，用户通过这个界面访问操作系统内核的服务, Shell脚本（shell script），是一种为Shell编写的脚本程序。我们经常说的shell通常都是指shell脚本。</p>
<h2 id="环境和工具"><a href="#环境和工具" class="headerlink" title="环境和工具"></a>环境和工具</h2><p>Shell跟java、php、Python编程一样，只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。</p>
<p>Mac OS，Linux 自带了shell解释器，Windows比较麻烦，没有内置shell解释器，可以自行安装<br>一个cygwin</p>
<h2 id="PHP、Python-也可以作为Shell编程"><a href="#PHP、Python-也可以作为Shell编程" class="headerlink" title="PHP、Python 也可以作为Shell编程"></a>PHP、Python 也可以作为Shell编程</h2><p>PHP、Python是属于高级编程语言，但是也可以做Shell编程，因为只要有解释器，也可以用作脚本编程</p>
<p>如下是一个Python Shell Script示例（假设文件名叫op_python_base.py）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#!/usr/bin/env python3 //告诉Python从系统环境中找python</span><br><span class="line"># -*- coding: utf-8 -*- //设置为UTF-8编码</span><br><span class="line"></span><br><span class="line">for index in range(10):</span><br><span class="line">    print(index);</span><br></pre></td></tr></table></figure>
<p>如下是一个PHP Shell Script示例（假设文件名叫op_php_base.php）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">#!/usr/bin/php</span><br><span class="line">&lt;?php</span><br><span class="line"></span><br><span class="line">for($i=0 ;$i&lt;10; $i++)&#123;</span><br><span class="line">    echo $i;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">?&gt;</span><br></pre></td></tr></table></figure>
<h2 id="为什么要学习Shell"><a href="#为什么要学习Shell" class="headerlink" title="为什么要学习Shell"></a>为什么要学习Shell</h2><p>既然PHP、Python都可以用来写脚本编程，那为什么还要学习陌生、晦涩难懂的Shell，主要有一下几个原因</p>
<ul>
<li><p>环境兼容性，因为除了windows，基本其他主流的操作系统都预制了Shell解释器，所以使用sh、bash编写，提供给其他人使用是非常方便的，但是PHP、Python 等等需要安装相应的环境</p>
</li>
<li><p>如果你想做一些定时任务比如说检测进程是否存在，自动备份，或者说自动部署环境、服务器之间的数据同步等等sh、bash会是你最好的选择</p>
</li>
</ul>
<h2 id="sh与bash"><a href="#sh与bash" class="headerlink" title="sh与bash"></a>sh与bash</h2><p>sh: Bourne shell，POSIX（Portable Operating System Interface）标准的shell解释器，它的二进制文件路径通常是/bin/sh</p>
<p>bash: Bash是Bourne shell的替代品，属GNU Project，二进制文件路径通常是/bin/bash</p>
<h2 id="第一个shell脚本"><a href="#第一个shell脚本" class="headerlink" title="第一个shell脚本"></a>第一个shell脚本</h2><h3 id="我们先来看一个例子"><a href="#我们先来看一个例子" class="headerlink" title="我们先来看一个例子"></a>我们先来看一个例子</h3><p>我相信写过代码的童鞋，应该对下面的代码很熟悉并不陌生，（假设文件名叫op_base.sh）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">#!/usr/bin/env bash</span><br><span class="line">mkdir code</span><br><span class="line">cd  code</span><br><span class="line">for ((i=0; i&lt;3; i++)); do</span><br><span class="line">    touch test_$&#123;i&#125;.txt</span><br><span class="line">    echo &quot;shell很简单&quot; &gt;&gt; test_$&#123;i&#125;.txt</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<p>第一行：从系统path中寻找指定脚本的解释程序<br>第二行：创建 名叫code文件夹<br>第三行：进入创建的文件夹<br>第四行：for循环3次<br>第四行：创建文件<br>第五行：往创建的文件中写入信息<br>第六行：结束循环</p>
<p>mkdir, touch，cd，touch，echo都是系统命令，在命令行下可以直接执行<br>for, do, done 是shell脚本语言 for循环的语法</p>
<h3 id="编写Shell"><a href="#编写Shell" class="headerlink" title="编写Shell"></a>编写Shell</h3><p>新建一个文件，扩展名为sh（sh代表shell），扩展名并不影响脚本执行，见名知意就好，如果你用php，扩展名为php，如果你用Python，扩展名为python</p>
<p>第一行一般是这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#!/usr/bin/php</span><br><span class="line">#!/usr/bin/env python3</span><br><span class="line">#!/usr/bin/env bash</span><br></pre></td></tr></table></figure>
<p> #!”是一个约定的标记，它告诉系统这个脚本需要什么解释器来执行<br>    /env 是系统的PATH目录中查找</p>
<h3 id="运行-Shell-脚本有两种方法："><a href="#运行-Shell-脚本有两种方法：" class="headerlink" title="运行 Shell 脚本有两种方法："></a>运行 Shell 脚本有两种方法：</h3><h4 id="作为可执行程序"><a href="#作为可执行程序" class="headerlink" title="作为可执行程序"></a>作为可执行程序</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">chmod +x op_base.sh</span><br><span class="line">./op_base.sh</span><br></pre></td></tr></table></figure>
<p>第一行设置 op_base.sh可执行权限<br>第二行执行op_base.sh</p>
<h4 id="作为参数"><a href="#作为参数" class="headerlink" title="作为参数"></a>作为参数</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/bin/sh op_base.sh</span><br></pre></td></tr></table></figure>
<h3 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h3><p>定义变量时，变量名前不需要加符号和Python一样但是在PHP语言中变量需要加$，如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">my_name=&quot;jack&quot;</span><br><span class="line">my_name=&apos;jack&apos;;</span><br></pre></td></tr></table></figure>
<p>ps: 变量名和等号之间不能有空格,变量后面不能有;</p>
<p>Shell中的引号和PHP类似，字符串可以用单引号，也可以用双引号</p>
<p>单引号字符串的限制：</p>
<ul>
<li>单引号里的任何字符都会原样输出，单引号字符串中的变量是无效的</li>
<li>单引号字串中不能出现单引号（对单引号使用转义符后也不行</li>
</ul>
<p>双引号：</p>
<ul>
<li>双引号里可以有变量</li>
<li>双引号里可以出现转义字符</li>
</ul>
<p>但是在Python中单引号和双引号是没有区别，但是Python 还有三个引号，在三个引号内字符都不会被转义</p>
<h3 id="使用变量"><a href="#使用变量" class="headerlink" title="使用变量"></a>使用变量</h3><p>对于已经定义过的变量，使用的适合在前面添加$</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">echo $my_name</span><br><span class="line">echo $&#123;my_name&#125;</span><br></pre></td></tr></table></figure>
<p>变量名外面的花括号是可选的，加不加都行,建议使用第二种形式</p>
<h3 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h3><p>以“#”开头的行就是注释，会被解释器忽略。</p>
<h4 id="多行注释"><a href="#多行注释" class="headerlink" title="多行注释"></a>多行注释</h4><p>sh里没有多行注释，只能每一行加一个#号。就像这样：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#--------------------------------------------</span><br><span class="line">#这里是注释</span><br><span class="line"># 还是注释</span><br><span class="line">#--------------------------------------------</span><br></pre></td></tr></table></figure>
<h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><p>字符串可以用单引号，也可以用双引号，也可以不用引号。单双引号的区别跟PHP类似</p>
<p>Shell不像其他语言有php、python 有很多数据类型，在Shell中常用的数据类型字符串数字和字符串（ps: 除了数字和字符串，也没啥其它类型好用了，哈哈）</p>
<p>单引号字符串的限制：</p>
<ul>
<li>单引号里的任何字符都会原样输出，单引号字符串中的变量是无效的</li>
<li>单引号字串中不能出现单引号（对单引号使用转义符后也不行</li>
</ul>
<p>双引号：</p>
<ul>
<li>双引号里可以有变量</li>
<li>双引号里可以出现转义字符</li>
</ul>
<h3 id="字符串操作"><a href="#字符串操作" class="headerlink" title="字符串操作"></a>字符串操作</h3><h4 id="拼接字符串"><a href="#拼接字符串" class="headerlink" title="拼接字符串"></a>拼接字符串</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">my_name=&quot;jack&quot;;</span><br><span class="line">my_age=&quot;20岁&quot;</span><br><span class="line">echo $my_name $my_age</span><br><span class="line">echo $my_name$my_age</span><br></pre></td></tr></table></figure>
<h4 id="获取字符串长度"><a href="#获取字符串长度" class="headerlink" title="获取字符串长度"></a>获取字符串长度</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">echo $&#123;#my_name&#125;</span><br></pre></td></tr></table></figure>
<h4 id="截取字符串"><a href="#截取字符串" class="headerlink" title="截取字符串"></a>截取字符串</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">echo $&#123;my_name:0:2&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Shell-数组"><a href="#Shell-数组" class="headerlink" title="Shell 数组"></a>Shell 数组</h3><h4 id="定义数组"><a href="#定义数组" class="headerlink" title="定义数组"></a>定义数组</h4><p>在Shell中，用括号来表示数组，数组元素用”空格”符号分割开。定义数组的一般形式为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">name=(name1 name2 name3)</span><br></pre></td></tr></table></figure>
<p>还可以单独定义数组的各个分量：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ary[0]=name1</span><br><span class="line">ary[1]=name2</span><br><span class="line">ary[3]=name3</span><br></pre></td></tr></table></figure>
<p>ps: 可以不使用连续的下标，而且下标的范围没有限制</p>
<h4 id="读取数组"><a href="#读取数组" class="headerlink" title="读取数组"></a>读取数组</h4><p>读取数组元素值的一般格式是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$&#123;数组名[下标]&#125;</span><br></pre></td></tr></table></figure>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">echo $&#123;name[0]&#125;</span><br></pre></td></tr></table></figure>
<p>使用@符号可以获取数组中的所有元素，例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">echo $&#123;name[@]&#125;</span><br></pre></td></tr></table></figure>
<h4 id="获取数组的长度"><a href="#获取数组的长度" class="headerlink" title="获取数组的长度"></a>获取数组的长度</h4><p>获取数组长度的方法与获取字符串长度的方法相同，例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 取得数组元素的个数</span><br><span class="line">length=$&#123;#name[@]&#125;</span><br><span class="line">echo $length</span><br><span class="line"></span><br><span class="line"># 或者</span><br><span class="line">length=$&#123;#name[*]&#125;</span><br><span class="line">echo $length</span><br><span class="line"></span><br><span class="line"># 取得数组单个元素的长度</span><br><span class="line">lengthn=$&#123;#name[n]&#125;</span><br><span class="line">echo $length</span><br></pre></td></tr></table></figure>
<h3 id="Shell-流程控制"><a href="#Shell-流程控制" class="headerlink" title="Shell 流程控制"></a>Shell 流程控制</h3><p>和Java、PHP、Python等语言不一样，sh的流程控制不可为空，如(以下为PHP流程控制写法)：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;?php</span><br><span class="line">if (isset($_GET[&quot;q&quot;])) &#123;</span><br><span class="line">    search(q);</span><br><span class="line">&#125;</span><br><span class="line">else &#123;</span><br><span class="line">    // 不做任何事情</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在sh/bash里可不能这么写，如果else分支没有语句执行，就不要写这个else</p>
<h4 id="if"><a href="#if" class="headerlink" title="if"></a>if</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">if condition1</span><br><span class="line">then</span><br><span class="line">    command1</span><br><span class="line">elif condition2 </span><br><span class="line">then </span><br><span class="line">    command2</span><br><span class="line">else</span><br><span class="line">    commandN</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>
<p>例子：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">#!/usr/bin/env bash</span><br><span class="line"></span><br><span class="line">a=1</span><br><span class="line">b=2</span><br><span class="line">if [ $a == $b ]</span><br><span class="line">    then</span><br><span class="line">        echo &quot;a 等于 b&quot;</span><br><span class="line"> elif [ $a -gt $b ]</span><br><span class="line">    then</span><br><span class="line">        echo &quot;a 大于 b&quot;</span><br><span class="line"> elif [ $a -lt $b ]</span><br><span class="line">    then</span><br><span class="line">        echo &quot;a 小于 b&quot;</span><br><span class="line"> else</span><br><span class="line">    echo &quot;没有符合的条件&quot;</span><br><span class="line"></span><br><span class="line"> fi</span><br></pre></td></tr></table></figure>
<h4 id="for-循环"><a href="#for-循环" class="headerlink" title="for 循环"></a>for 循环</h4><p>Shell的for循环和Python 有点类似</p>
<h5 id="Python的for循环"><a href="#Python的for循环" class="headerlink" title="Python的for循环"></a>Python的for循环</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">for index in 1,2,3,4,5:</span><br><span class="line">    print(index);</span><br></pre></td></tr></table></figure>
<h5 id="Shell的for循环，第一种写法"><a href="#Shell的for循环，第一种写法" class="headerlink" title="Shell的for循环，第一种写法"></a>Shell的for循环，第一种写法</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">for index in 1 2 3 4 5; do</span><br><span class="line">    echo &quot;index=&quot;$index</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<h5 id="Shell的for循环，第二种写法"><a href="#Shell的for循环，第二种写法" class="headerlink" title="Shell的for循环，第二种写法"></a>Shell的for循环，第二种写法</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">for ((i=0; i&lt;5; i++)); do</span><br><span class="line">    echo &quot;i=&quot;$i</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<h4 id="while-语句"><a href="#while-语句" class="headerlink" title="while 语句"></a>while 语句</h4><p>while循环用于不断执行一系列命令，也用于从输入文件中读取数据；命令通常为测试条件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">int=1</span><br><span class="line">while(( $int&lt;=5 ))</span><br><span class="line">do</span><br><span class="line">    echo $int</span><br><span class="line">    let &quot;int++&quot;</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<h3 id="Shell结合系统命令"><a href="#Shell结合系统命令" class="headerlink" title="Shell结合系统命令"></a>Shell结合系统命令</h3><p>sh脚本结合系统命令便有了强大的威力，在字符处理领域，有grep、awk、sed三剑客，grep负责找出特定的行，awk能将行拆分成多个字段，sed则可以实现更新插入删除等写操作。</p>
<h4 id="例如定时检测nginx、mysql是否被关闭"><a href="#例如定时检测nginx、mysql是否被关闭" class="headerlink" title="例如定时检测nginx、mysql是否被关闭"></a>例如定时检测nginx、mysql是否被关闭</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">path=/var/log</span><br><span class="line">log=$&#123;path&#125;/httpd-mysql.log</span><br><span class="line"></span><br><span class="line">name=(apache mysql)</span><br><span class="line"></span><br><span class="line">exs_init[0]=&quot;service httpd start&quot;</span><br><span class="line">exs_init[1]=&quot;/etc/init.d/mysqld restart&quot;</span><br><span class="line"></span><br><span class="line">for ((i=0; i&lt;2; i++)); do</span><br><span class="line">    echo &quot;检查$&#123;name[i]&#125;进程是否存在&quot;</span><br><span class="line">    ps -ef|grep $&#123;name[i]&#125; |grep -v grep</span><br><span class="line">    if [ $? -eq 0 ]; then</span><br><span class="line">        pid=$(pgrep -f $&#123;name[i]&#125;)</span><br><span class="line">        echo &quot;`date +&quot;%Y-%m-%d %H:%M:%S&quot;` $&#123;name[$i]&#125; is running with pid $pid&quot; &gt;&gt; $&#123;log&#125;</span><br><span class="line">     else</span><br><span class="line">        $($&#123;exs_init[i]&#125;)</span><br><span class="line">        echo &quot;`date +&quot;%Y-%m-%d %H:%M:%S&quot;` $&#123;name[$i]&#125; start success&quot; &gt;&gt; $&#123;log&#125;</span><br><span class="line">    fi</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<p>解释：检测 nginx、mysql进程是否存在，如果不存在了会自动重新启动。<br>脚本每次运行会写日志的，没事可以去看看该日志文件，如果进程是不是真的经常性不存在，恐怕就要排查一下深层原因了。</p>
<h4 id="编辑-etc-crontab-文件"><a href="#编辑-etc-crontab-文件" class="headerlink" title="编辑 /etc/crontab 文件"></a>编辑 /etc/crontab 文件</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">crontab -e</span><br></pre></td></tr></table></figure>
<p>在文件最后添加一行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">*/5 * * * * /xxx/check_nginx.sh &gt; /dev/null 2&gt;&amp;1</span><br></pre></td></tr></table></figure>
<p>上表示每 5 分钟，执行一下脚本 /xxx/check_nginx.sh，其中xxx代表路径</p>
<p>/dev/null 2&gt;&amp;1 的意思是该条shell命令将不会输出任何信息到控制台，也不会有任何信息输出到文件中。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">#cron表达式每个位置的含义</span><br><span class="line"># For details see man 4 crontabs</span><br><span class="line"></span><br><span class="line"># Example of job definition:</span><br><span class="line"># .---------------- minute (0 - 59)</span><br><span class="line"># |  .------------- hour (0 - 23)</span><br><span class="line"># |  |  .---------- day of month (1 - 31)</span><br><span class="line"># |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...</span><br><span class="line"># |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat</span><br><span class="line"># |  |  |  |  |</span><br><span class="line"># *  *  *  *  * command to be executed</span><br></pre></td></tr></table></figure>
<h3 id="添加完配置，重启才能生效"><a href="#添加完配置，重启才能生效" class="headerlink" title="添加完配置，重启才能生效"></a>添加完配置，重启才能生效</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">service crond restart</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/教程/" rel="tag"># 教程</a>
          
            <a href="/tags/shell/" rel="tag"># shell</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/12/20/vue/vue-bootstrap-page/" rel="next" title="vue bootstrap  带分页表格">
                <i class="fa fa-chevron-left"></i> vue bootstrap  带分页表格
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/20/websocket/websocket/" rel="prev" title="websocket 断线重连方案">
                websocket 断线重连方案 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="李磊">
            
              <p class="site-author-name" itemprop="name">李磊</p>
              <p class="site-description motion-element" itemprop="description">不做键盘侠！！！</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/mylyed" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github-alt"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://git.oschina.net/lil" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-gitlab"></i>码云</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://weibo.com/u/2168032422" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/li-cai-40-13" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Shell是什么"><span class="nav-number">1.</span> <span class="nav-text">Shell是什么</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#环境和工具"><span class="nav-number">2.</span> <span class="nav-text">环境和工具</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PHP、Python-也可以作为Shell编程"><span class="nav-number">3.</span> <span class="nav-text">PHP、Python 也可以作为Shell编程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么要学习Shell"><span class="nav-number">4.</span> <span class="nav-text">为什么要学习Shell</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#sh与bash"><span class="nav-number">5.</span> <span class="nav-text">sh与bash</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#第一个shell脚本"><span class="nav-number">6.</span> <span class="nav-text">第一个shell脚本</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#我们先来看一个例子"><span class="nav-number">6.1.</span> <span class="nav-text">我们先来看一个例子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写Shell"><span class="nav-number">6.2.</span> <span class="nav-text">编写Shell</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行-Shell-脚本有两种方法："><span class="nav-number">6.3.</span> <span class="nav-text">运行 Shell 脚本有两种方法：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#作为可执行程序"><span class="nav-number">6.3.1.</span> <span class="nav-text">作为可执行程序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#作为参数"><span class="nav-number">6.3.2.</span> <span class="nav-text">作为参数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#变量"><span class="nav-number">6.4.</span> <span class="nav-text">变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用变量"><span class="nav-number">6.5.</span> <span class="nav-text">使用变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注释"><span class="nav-number">6.6.</span> <span class="nav-text">注释</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#多行注释"><span class="nav-number">6.6.1.</span> <span class="nav-text">多行注释</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串"><span class="nav-number">6.7.</span> <span class="nav-text">字符串</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串操作"><span class="nav-number">6.8.</span> <span class="nav-text">字符串操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#拼接字符串"><span class="nav-number">6.8.1.</span> <span class="nav-text">拼接字符串</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取字符串长度"><span class="nav-number">6.8.2.</span> <span class="nav-text">获取字符串长度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#截取字符串"><span class="nav-number">6.8.3.</span> <span class="nav-text">截取字符串</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Shell-数组"><span class="nav-number">6.9.</span> <span class="nav-text">Shell 数组</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#定义数组"><span class="nav-number">6.9.1.</span> <span class="nav-text">定义数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#读取数组"><span class="nav-number">6.9.2.</span> <span class="nav-text">读取数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取数组的长度"><span class="nav-number">6.9.3.</span> <span class="nav-text">获取数组的长度</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Shell-流程控制"><span class="nav-number">6.10.</span> <span class="nav-text">Shell 流程控制</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#if"><span class="nav-number">6.10.1.</span> <span class="nav-text">if</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#for-循环"><span class="nav-number">6.10.2.</span> <span class="nav-text">for 循环</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#Python的for循环"><span class="nav-number">6.10.2.1.</span> <span class="nav-text">Python的for循环</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Shell的for循环，第一种写法"><span class="nav-number">6.10.2.2.</span> <span class="nav-text">Shell的for循环，第一种写法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Shell的for循环，第二种写法"><span class="nav-number">6.10.2.3.</span> <span class="nav-text">Shell的for循环，第二种写法</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#while-语句"><span class="nav-number">6.10.3.</span> <span class="nav-text">while 语句</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Shell结合系统命令"><span class="nav-number">6.11.</span> <span class="nav-text">Shell结合系统命令</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#例如定时检测nginx、mysql是否被关闭"><span class="nav-number">6.11.1.</span> <span class="nav-text">例如定时检测nginx、mysql是否被关闭</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#编辑-etc-crontab-文件"><span class="nav-number">6.11.2.</span> <span class="nav-text">编辑 /etc/crontab 文件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加完配置，重启才能生效"><span class="nav-number">6.12.</span> <span class="nav-text">添加完配置，重启才能生效</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user-secret"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">李磊</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a></div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
